package com.eshore.norm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.eshore.norm.pojo.constant.Const;
import com.eshore.norm.pojo.dto.NormHost;
import com.eshore.norm.pojo.dto.NormVmVolumeAttach;
import com.eshore.norm.pojo.dto.NormVolume;
import com.eshore.norm.mapper.NormVolumeMapper;
import com.eshore.norm.pojo.po.NormResourceProvidersPO;
import com.eshore.norm.pojo.po.NormVolumeDetailPO;
import com.eshore.norm.pojo.po.cmdb.CmdbVolume;
import com.eshore.norm.pojo.po.volume.NormSyncVolumePO;
import com.eshore.norm.service.INormVolumeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 存储卷详情列表 服务实现类
 * </p>
 *
 * @author chenjl
 * @since 2024-01-05
 */
@Slf4j
@Service
public class NormVolumeServiceImpl extends ServiceImpl<NormVolumeMapper, NormVolume> implements INormVolumeService {

    @Override
    public void dataImport(NormVolumeDetailPO po) {
        if (po != null) {
            log.info("po:{}", po.getVolumes());
            List<NormVolumeDetailPO.VolumesDTO> volumesDTOList = po.getVolumes();
            if (!CollectionUtils.isEmpty(volumesDTOList)) {
                //开始处理源数据 将其包装成NormVolume和NormVmVolumeAttach
                NormSyncVolumePO normSyncVolumePO = handleVolumes(Const.CONFIG_ID, volumesDTOList);
                //处理硬盘
                List<NormVolume> volumes = normSyncVolumePO.getVolumes();
                List<String> newIds = volumes.stream().map(NormVolume::getVolumesDetailId).collect(Collectors.toList());
                List<String> removeVolumesDetailId = cleanVolumeOldData(Const.CONFIG_ID, newIds);
                getBaseMapper().insertOrUpdate(volumes);

                //TODO 同步到cmdb
                syncVolumeCmdb(volumes, removeVolumesDetailId, Const.TENANT_CODE);

                //处理虚机硬盘中间关系
//                List<NormVmVolumeAttach> attaches = normSyncVolumePO.getVmVolumeAttaches();
//                vmVolumeAttachService.sync(c.getId(), attaches);
            }
        }
    }

    private void syncVolumeCmdb(List<NormVolume> volumeList, List<String> oldVolumeIds,Long tenantCode) {
        //搞不懂为何id没值
        log.info("volumeList:"+volumeList);
        if (CollectionUtil.isNotEmpty(volumeList)) {
            List<CmdbVolume> syncInfoList = volumeList.stream().map(t -> {
                CmdbVolume volumeVO = new CmdbVolume();
                BeanUtil.copyProperties(t, volumeVO);
                volumeVO.setId(t.getId());
                volumeVO.setName(t.getName());
              //  volumeVO.setCloudType(CloudTypeEnum.PRIVATE);
                volumeVO.setTenantCode(tenantCode);
             //   volumeVO.setVirtualizationType(CmdbResTypeEnums.NORM);
                //volumeVO.setProjectId(t.getProjectId());
                volumeVO.setAccountId(t.getConfigId());
                volumeVO.setVolumeId(t.getVolumesDetailId());
                volumeVO.setSize(t.getSize());
                volumeVO.setStatus(t.getStatus());
                volumeVO.setAvailabilityZone(t.getAvailabilityZone());
                return volumeVO;
            }).collect(Collectors.toList());
            log.info("syncInfoList:"+syncInfoList);
            //同步到cmdb
//            SyncMessageContent<CmdbVolume> messageContent = new SyncMessageContent<>();
//            messageContent.setCloudType(SyncMessageContent.CLOUD_TYPE_NORM_CLOUD);
//            messageContent.setResourceType(SyncMessageContent.RESOURCE_TYPE_SYNC_VOLUME);
//            messageContent.setAddOrUpdateDatas(syncInfoList);
//            messageContent.setRemoveStrIds(oldVolumeIds);
//            rabbitService.defaultDirectSend(SyncMessageContent.QUEUE_NAME, JSONObject.toJSONString(messageContent));
        }
    }

    private List<String> cleanVolumeOldData(Long configId, List<String> newIds) {
        //查出原来的旧数据
        List<String> oldVolumeIds = lambdaQuery().eq(NormVolume::getConfigId, configId).list().stream().map(NormVolume::getVolumesDetailId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(oldVolumeIds)){
            oldVolumeIds.removeAll(newIds);
            if (!CollectionUtils.isEmpty(oldVolumeIds)){
                lambdaUpdate().in(NormVolume::getVolumesDetailId,oldVolumeIds).remove();
                return oldVolumeIds;
            }
        }
        return null;
    }


    private NormSyncVolumePO handleVolumes(Long configId, List<NormVolumeDetailPO.VolumesDTO> volumes) {
        NormSyncVolumePO po = new NormSyncVolumePO();
        List<NormVolume> volumeList = new ArrayList<>();
        List<NormVmVolumeAttach> vmVolumeAttachList = new ArrayList<>();
        volumes.forEach(v -> {
            //先处理硬盘基础数据
            NormVolume volume = new NormVolume();
            BeanUtils.copyProperties(v, volume, "id");
            volume.setId(IdWorker.getId());
            volume.setConfigId(configId);
            volume.setCreateDate(DateUtil.parseUTC(v.getCreatedAt()));
            volume.setUpdateDate(DateUtil.parseUTC(v.getUpdatedAt()));
            volume.setMigrationStatus(v.getMigrationStatus());
            volume.setVolumesDetailId(v.getId());
            volume.setOsVolHostAttrHost(v.getHost());
            volumeList.add(volume);
            //处理虚机硬盘中间表
            List<NormVolumeDetailPO.VolumesDTO.AttachmentsDTO> attachments = v.getAttachments();
            if (!CollectionUtils.isEmpty(attachments)) {
                attachments.forEach(a -> {
                    NormVmVolumeAttach attach = new NormVmVolumeAttach();
                    attach.setId(IdWorker.getId());
                    attach.setVolumeId(a.getVolumeId());
                    attach.setServerId(a.getServerId());
                    attach.setDevice(a.getDevice());
                    attach.setAttachedAt(a.getAttachedAt());
                    attach.setConfigId(configId);
                    attach.setHostName(a.getHostName());
                    vmVolumeAttachList.add(attach);
                });
            }
        });
        po.setVolumes(volumeList);
        po.setVmVolumeAttaches(vmVolumeAttachList);
        return po;
    }

}
